package Service;

import entity.User;
import org.json.JSONObject;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/**
 * @Author Su
 * @Date 2025/4/30 22:42
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/comment")
public class CommentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        JSONObject responseJson = new JSONObject();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            HttpSession session = req.getSession(false);
            if (session == null) {
                responseJson.put("code", 401);
                responseJson.put("message", "未登录");
                return;
            }

            User user = (User) req.getSession().getAttribute("user");
            conn = DBUtil.getConnection();
            System.out.println(req.getParameter("articleId"));
            int articleId = Integer.parseInt(req.getParameter("articleId"));

            String content = req.getParameter("content");
            System.out.println(req.getParameter("parentId"));
            Integer parentId = req.getParameter("parentId") != null ?
                    Integer.parseInt(req.getParameter("parentId")) : null;
            System.out.println("0");
            // 检查文章是否存在
            pstmt = conn.prepareStatement("SELECT id FROM articles WHERE id = ?");
            pstmt.setInt(1, articleId);
            System.out.println("1");
            rs = pstmt.executeQuery();
            if (!rs.next()) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Article not found");
                return;
            }

            // 处理父评论
            Integer rootId = null;
            if (parentId != null) {
                pstmt = conn.prepareStatement(
                        "SELECT root_id FROM article_comments WHERE id = ?");
                pstmt.setInt(1, parentId);
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    rootId = rs.getInt("root_id");
                    if (rs.wasNull()) rootId = parentId;
                } else {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parent comment");
                    return;
                }
            }
            System.out.println("2");
            // 插入评论
            pstmt = conn.prepareStatement(
                    "INSERT INTO article_comments (article_id, user_id, parent_id, root_id, content) " +
                            "VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
            pstmt.setInt(1, articleId);
            pstmt.setInt(2, user.getUserId());
            if (parentId != null) {
                pstmt.setInt(3, parentId);
                pstmt.setInt(4, rootId);
            } else {
                pstmt.setNull(3, Types.INTEGER);
                pstmt.setNull(4, Types.INTEGER);
            }
            pstmt.setString(5, content);
            pstmt.executeUpdate();
            System.out.println("3");
            // 获取新评论ID
            rs = pstmt.getGeneratedKeys();
            if (rs.next()) {
                int commentId = rs.getInt(1);
                resp.setContentType("application/json");
                resp.getWriter().write(String.format(
                        "{\"id\": %d, \"userId\": %d, \"content\": \"%s\"}",
                        commentId, user.getUserId(), content));
            }

        } catch (SQLException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            resp.getWriter().print(responseJson.toString());
            DBUtil.closeConnection(conn);
        }
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        int articleId = Integer.parseInt(req.getParameter("articleId"));
        Integer rootId = req.getParameter("rootId") != null ?
                Integer.parseInt(req.getParameter("rootId")) : null;

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql;
            if (rootId != null) {
                sql = "SELECT * FROM article_comments WHERE article_id = ? AND root_id = ? ORDER BY created_at DESC";
                pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, articleId);
                pstmt.setInt(2, rootId);
            } else {
                sql = "SELECT * FROM article_comments WHERE article_id = ? AND root_id IS NULL ORDER BY created_at DESC";
                pstmt = conn.prepareStatement(sql);
                pstmt.setInt(1, articleId);
            }

            rs = pstmt.executeQuery();

            // 构建JSON响应
            resp.setContentType("application/json");
            PrintWriter out = resp.getWriter();
            out.print("[");
            boolean first = true;
            while (rs.next()) {
                if (!first) out.print(",");
                out.print(String.format(
                        "{\"id\": %d, \"userId\": %d, \"content\": \"%s\", \"createdAt\": \"%s\"}",
                        rs.getInt("id"),
                        rs.getInt("user_id"),
                        rs.getString("content"),
                        rs.getTimestamp("created_at").toString()));
                first = false;
            }
            out.print("]");

        } catch (SQLException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            DBUtil.closeConnection(conn);
        }
    }
}
